﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using TY.UC.Common;
using TY.UC.Common.Extension;
using TY.UC.Http;

namespace TY.UT.Push.YouMeng
{
    /// <summary> 
    /// add by 廖宇 2016.09.29
    /// 推送帮助
    /// </summary>
    public class YouMengPushHelper
    {
        #region 配置文件

        private static readonly string IosAppKey = "YMIosAppKey".GetStrValue();
        private static readonly string IosAppSecret = "YMIosAppSecret".GetStrValue();
        private static readonly string PushUrl = "YMPushUrl".GetStrValue();
        private static readonly string IosIsProduct = "IosIsProduct".GetStrValue();

        private static readonly string AndroidAppKey = "YMAndroidAppKey".GetStrValue();
        private static readonly string AndroidMessageSecret = "YMAndroidMessageSecret".GetStrValue();
        private static readonly string AndroidMasterSecret = "YMAndroidMasterSecret".GetStrValue();
        private static readonly string AndroidIsProduct = "AndroidIsProduct".GetStrValue();

        #endregion

        #region 推送方法

        /// <summary>
        /// add by 廖宇 2016.09.29
        /// IOS推送
        /// </summary>
        /// <param name="content">信息内容</param>
        /// <param name="castType">推送方式：
        /// unicast-单播
        /// listcast-列播(要求不超过500个device_token)
        /// filecast-文件播 (多个device_token可通过文件形式批量发送）
        /// broadcast-广播
        /// groupcast-组播
        /// (按照filter条件筛选特定用户群, 具体请参照filter参数)
        /// customizedcast(通过开发者自有的alias进行推送)
        /// </param>
        /// <param name="aliasType">别名类型</param>
        /// <param name="alias">别名</param>
        /// <param name="description">描述</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool IosMessagePush(string content, string castType,string aliasType, string alias, string description, out string msg)
        {
            msg = "";
            IosMsgModel msgModel = new IosMsgModel
            {
                AppKey = IosAppKey,
                Type = castType,
                AliasType = aliasType,
                Alias = alias,
                DeviceToken = "",//设置为null会json解析错误
                ProductMode = IosIsProduct,
                Description = description,
                PaLoadMsg = new IosPayLoad
                {
                    Msg = new IosMsg
                    {
                        Alert = content,
                        Badge=1,
                    }
                },
                PolicySet = new IosPolicy
                {
                    ExpireTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"),
                }
            };

            string param = JsonConvert.SerializeObject(msgModel);

            string sign = "POST" + PushUrl + param + IosAppSecret;
            sign = Md5Helper.Get32Md5Str(sign);
            string postUrl = PushUrl + "?sign=" + sign;

            try
            {
                string json = HttpHelper.JsonStrPostRequest(param, postUrl);

                Dictionary<string, object> res = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                if (res["ret"] + "" == "SUCCESS")
                {
                    return true;
                }
                msg = "调用友盟推送IOS信息，友盟返回失败信息";
                LogHelper.WriteLog("Push", "YouMengPushHelper-IosMessagePush,调用友盟推送IOS信息，友盟返回失败信息，入参：" + param + ",错误信息=" + res["data"] + "[IosAppKey]=" +
                                   IosAppKey + ",[IosAppSecret]=" + IosAppSecret + ",[PushUrl]=" + PushUrl + "[IosIsProduct]=" + IosIsProduct);
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.ProtocolError) return false;
                Stream myResponseStream = ((HttpWebResponse)e.Response).GetResponseStream();
                if (myResponseStream == null) return false;
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                msg = retString;
                LogHelper.WriteLog("Push", "YouMengPushHelper-IosMessagePush,调用友盟推送IOS信息，友盟返回失败信息，入参：" + param + "[IosAppKey]=" + IosAppKey + ",[IosAppSecret]=" +
                                   IosAppSecret + ",[PushUrl]=" + PushUrl + "[IosIsProduct]=" + IosIsProduct + ",错误信息=" + retString, e);
            }
            catch (Exception e)
            {
                msg = "调用友盟推送IOS信息发生异常";
                LogHelper.WriteLog("Push", "YouMengPushHelper-IosMessagePush,调用友盟推送IOS信息发生异常，入参：" + param + "[IosAppKey]=" + IosAppKey + ",[IosAppSecret]=" +
                                       IosAppSecret + ",[PushUrl]=" + PushUrl + "[IosIsProduct]=" + IosIsProduct, e);
            }
            return false;
        }

        /// <summary> 
        /// add by 廖宇 2016.10.27
        /// Android推送
        /// </summary>
        /// <param name="ticker">消息描述</param>
        /// <param name="title">消息标题</param>
        /// <param name="text">消息内容</param>
        /// <param name="castType">推送方式：     
        ///  /// unicast-单播
        /// listcast-列播(要求不超过500个device_token)
        /// filecast-文件播 (多个device_token可通过文件形式批量发送）
        /// broadcast-广播
        /// groupcast-组播
        /// (按照filter条件筛选特定用户群, 具体请参照filter参数)
        /// customizedcast(通过开发者自有的alias进行推送)
        /// </param>
        /// <param name="aliasType">别名类型</param>
        /// <param name="alias">别名</param>
        /// <param name="description">描述</param>
        /// <param name="msg">错误信息</param>
        /// <returns></returns>
        public static bool AndroidMessagePush(string ticker,string title,string text, string castType, string aliasType, string alias, string description, out string msg)
        {
            msg = "";
            AndroidMsgModel msgModel = new AndroidMsgModel
            {
                AppKey = AndroidAppKey,
                Type = "customizedcast",
                AliasType = aliasType,
                Alias = alias,
                DeviceToken = "",//设置为null会json解析错误
                ProductMode = AndroidIsProduct,
                Description = description,
                PaLoadMsg = new AndroidPayLoad
                {
                    DisplayType= "notification",
                    MsgBody = new AndroidBody
                    {
                        Ticker = ticker,
                        Title = title,
                        Text = text,
                        AfterOpen = "go_app",
                    }
                },
                PolicySet = new AndroidPolicy
                {
                    ExpireTime = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"),
                }
            };

            string param = JsonConvert.SerializeObject(msgModel);

            string sign = "POST" + PushUrl + param + AndroidMasterSecret;
            sign = Md5Helper.Get32Md5Str(sign);
            string postUrl = PushUrl + "?sign=" + sign;

            try
            {
                string json = HttpHelper.JsonStrPostRequest(param, postUrl);

                Dictionary<string, object> res = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
                if (res["ret"] + "" == "SUCCESS")
                {
                    return true;
                }
                msg = "调用友盟推送Android信息，友盟返回失败信息";
                LogHelper.WriteLog("Push", "YouMengPushHelper-AndroidMessagePush,调用友盟推送Android信息，友盟返回失败信息，入参：" + param + ",错误信息=" + res["data"] + "[AndroidAppKey]=" +
                                   AndroidAppKey + ",[AndroidMasterSecret]=" + AndroidMasterSecret + ",[PushUrl]=" + PushUrl + "[AndroidIsProduct]=" + AndroidIsProduct);
            }
            catch (WebException e)
            {
                if (e.Status != WebExceptionStatus.ProtocolError) return false;
                Stream myResponseStream = ((HttpWebResponse)e.Response).GetResponseStream();
                if (myResponseStream == null) return false;
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                msg = retString;
                LogHelper.WriteLog("Push", "YouMengPushHelper-AndroidMessagePush,调用友盟推送Android信息，友盟返回失败信息，入参：" + param + "[AndroidAppKey]=" + AndroidAppKey + ",[AndroidMasterSecret]=" +
                                   AndroidMasterSecret + ",[PushUrl]=" + PushUrl + "[AndroidIsProduct]=" + AndroidIsProduct + ",错误信息=" + retString, e);
            }
            catch (Exception e)
            {
                msg = "调用友盟推送IOS信息发生异常";
                LogHelper.WriteLog("Push", "YouMengPushHelper-AndroidMessagePush,调用友盟推送Android信息发生异常，入参：" + param + "[AndroidAppKey]=" + AndroidAppKey + ",[AndroidMasterSecret]=" +
                                       AndroidMasterSecret + ",[PushUrl]=" + PushUrl + "[AndroidIsProduct]=" + AndroidIsProduct, e);
            }
            return false;
        }

        #endregion
    }

}

